layui.config({
	base : "../../js/"
}).extend({
	"utilObj":"utilObj",
	"rate":"rate"
})
layui.use(['utilObj','form','layer','laydate','table','laytpl','laypage','util','rate'],function(){
	
	var utilObj = layui.utilObj;//自定义模块，包含ajax
	var laypage = layui.laypage;
	var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;
    
    var page={
    	getStore:function(){
    		utilObj.ajax({
				url: "cms/appoint/getStoreList",
				success: function(data){
					if(data){
						for(var obj of data){
							$("[name='search_EQ_store__id']").append(`<option value="${obj.id}">${obj.name}</option>`);
						}
						form.render('select',"store");
					}
				}
			});
    	},
    	getData:function(pageIndex){
    		var d={
				pageSize:utilObj.pageSize,
				pageIndex:pageIndex-1,
				jsonFilter:""
			};
			
			if(window.remindDate){
				page.searchData={
					arriveDate:window.remindDate
				};
			}
			
			if(page.searchData){
				var arriveDate=page.searchData.arriveDate;
				if(arriveDate && arriveDate!=""){
					var t= arriveDate.split(' - ');
					if(window.remindDate){
						page.searchData.search_GTE_appointTime=t[0];
						page.searchData.search_LTE_appointTime=t[1];
					}else{
						page.searchData.search_GTE_appointTime=t[0]+" 00:00:00";
						page.searchData.search_LTE_appointTime=t[1]+" 00:00:00";
					}
				}
				var createDate=page.searchData.createDate;
				if(createDate && createDate!=""){
					var t= createDate.split(' - ');
					page.searchData.search_GTE_createTime=t[0]+" 00:00:00";
					page.searchData.search_LTE_createTime=t[1]+" 00:00:00";
				}
				d.jsonFilter=JSON.stringify(page.searchData);
			}
			delete window.remindDate;
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/findByConditionsPage",
				data: d,
				success: function(data){
					if(data && data.content){
						var tableIns = table.render({
					        elem: '#list',
					        cellMinWidth : 95,
					//      page : true,
							limit:utilObj.pageSize,
					        height : "full-270",
					        id : "list",
					        cols : [[
					            {field: 'phone', title: '客户电话', align:"center",width:150},
					            {field: 'store', title: '预约店铺', align:'center',width:250,templet:function(d){
					            	return d.store.name;
					            }},
					            {field: 'name', title: '客户姓名', align:'center',width:120},
					            {field: 'appointTime', title: '客户预约到店时间', align:'center',width:200,templet:function(d){
					            	return layui.util.toDateString(new Date(d.appointTime));
					            }},
					            {field: 'status', title: '预约到店状态', align:'center',width:120,templet:function(d){
					            	//0-待反馈,1-已接受,2-已取消,3-到店购买,4-到店未购买,5-未到店,6-已评价
					            	var str='';
					            	if(d.status==0){
					            		str+='待处理';
					            	}
					            	else if(d.status==1){
					            		str+='已接受';
					            	}
					            	else if(d.status==2){
					            		str+='已取消';
					            	}
					            	else if(d.status==3){
					            		str+='到店并购买';
					            	}
					            	else if(d.status==4){
					            		str+='到店未购买';
					            	}
					            	else if(d.status==5){
					            		str+='未到店';
					            	}
					            	else if(d.status==6){
					            		str+='已评价';
					            	}
					            	return str;
					            }},
					            {field: 'newsAuthor2', title: '店铺联系人', align:'center',width:120,templet:function(d){
					            	return d.store.contact || "";
					            }},
					            {field: 'newsAuthor3', title: '店铺联系电话', align:'center',width:360,templet:function(d){
					            	return (d.store.contactNumber || "") + (d.store.contactNumber?" - ":"") + (d.store.phone || "");
					            }},
					            {field: 'memo', title: '客户备注内容', align:'center',width:200},
					            {field: 'image', title: '客户图片上传(双击查看)', align:'center',width:200,templet:function(d){
					            	var r='';
					            	for(var i=1;i<=3;i++){
					            		if(d["image"+i]){
					            			r+='<div img="'+ d["image"+i] +'" class="table-cell-image" style="background-image:url('+ d["image"+i] +')"></div>';
					            		}
					            	}
					            	return r;
					            }},
					            {field: 'createTime', title: '客户预约创建时间', align:'center',width:200,templet:function(d){
					            	return layui.util.toDateString(new Date(d.createTime));
					            }},
					            {field: 'newsAuthor9', title: '客服负责人', align:'center',width:150,templet:function(d){
					            	return (d.adminUser && d.adminUser.userName) || "";
					            }},
					            {field: 'followMemo', title: '预约跟进反馈', align:'center',width:360},
					            
					            
			//		            {field: 'newsStatus', title: '客户姓名',  align:'center',templet:"#newsStatus"},
			//		            {field: 'newsLook', title: '浏览权限', align:'center'},
			//		            {field: 'newsTop', title: '是否置顶', align:'center', templet:function(d){
			//		                return '<input type="checkbox" name="newsTop" lay-filter="newsTop" lay-skin="switch" lay-text="是|否" '+d.newsTop+'>'
			//		            }},
			//		            {field: 'newsTime', title: '发布时间', align:'center', minWidth:110, templet:function(d){
			////		                return d.newsTime.substring(0,10);
			//		            }},
					            {title: '操作', width:180,fixed:"right",align:"center",templet:function(d){
					            	var str='';
					            	//0-待反馈,1-已接受,2-已取消,3-到店购买,4-到店未购买,5-未到店,6-已评价
					            	if(d.status==0){
					            		if(!d.adminUser){//如果没有人接单
					            			str+='<a class="layui-btn layui-btn-xs" lay-event="process">我来处理</a>';
					            		}
					            		else if(d.adminUser && d.adminUser.id==utilObj.getUser().userId){//我的单子
					            			str+='<a class="layui-btn layui-btn-xs" lay-event="accept">接受</a>';
					            			str+='<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="cancel">取消</a>';
					            		}
					            	}
					            	else if(d.status==1 && d.adminUser && d.adminUser.id==utilObj.getUser().userId){
					            		str+='<a class="layui-btn layui-btn-xs" lay-event="isArrive">是否到店</a>';
					            	}
					            	else if(d.status==2){
					            		str+='<a class="layui-btn layui-btn-xs" lay-event="reasonCancel">取消原因</a>';
					            	}
//					            	else if(d.status==3 || d.status==4){
//					            		str+='<a class="layui-btn layui-btn-xs" lay-event="evaluate">评价</a>';
//					            	}
					            	else if(d.status==5){
					            		str+='<a class="layui-btn layui-btn-xs" lay-event="reasonArrive">未到店原因</a>';
					            	}
					            	else if(d.status==6){
					            		str+='<a class="layui-btn layui-btn-xs" lay-event="evaluateView">查看评价</a>';
					            	}
					            	
				            		str+='<a class="layui-btn layui-btn-xs" lay-event="append">跟进记录</a>';
					            	
					            	return str;
					            }},
					        ]],
					        data:data.content,
					        done:function(res, curr, count){
					        	$.each(res.data, function(i,d) {
 						        	if((d.adminUser && d.adminUser.id!=utilObj.getUser().userId)){//不是自己接的单子，变灰
					            		$("tr[data-index='"+ d.LAY_TABLE_INDEX +"']").css("background-color","lightgray");
					            	}
					        		
					        	});
					        }
					    });
					    laypage.render({
						    elem: 'pagination',
						    curr:pageIndex,
						    count: data.totalElements,
						    limit:utilObj.pageSize,
						    jump: function(obj,first){
						    	page.current=obj.curr;
						    	if(!first){
						    		page.getData(obj.curr);
							    }
						    }
						});
					}
					utilObj.hideLoading();
				},
				error:function(){
					utilObj.hideLoading();
				}
			});
    	},
    	process:function(data){
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/giveMe",
				data:{
					userId:utilObj.getUser().userId,
					appoinId:data.id,
				},
				success: function(data){
					if(data){
						page.getData(page.current);
					}
					utilObj.hideLoading();
				}
			});
    	},
    	cancel:function(data,remark){
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/reject",
				data:{
					userId:utilObj.getUser().userId,
					appoinId:data.id,
					reason:remark
				},
				success: function(data){
					if(data){
						page.getData(page.current);
					}
					utilObj.hideLoading();
				}
			});
    	},
    	accept:function(data){
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/accept",
				data:{
					userId:utilObj.getUser().userId,
					appoinId:data.id,
				},
				success: function(data){
					if(data){
						page.getData(page.current);
					}
					utilObj.hideLoading();
				}
			});
    	},
    	arrive:function(appointId,status,remark){
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/arriveRecord",
				data:{
					userId:utilObj.getUser().userId,
					appoinId:appointId,
					status:status,
					reason:remark
				},
				success: function(data){
					if(data){
						page.getData(page.current);
					}
					utilObj.hideLoading();
				}
			});
    	},
    	evaluate:function(appointId,star,remark){
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/saveRate",
				data:{
					userId:utilObj.getUser().userId,
					appoinId:appointId,
					score:star,
					scoreMemo:remark
				},
				success: function(data){
					if(data){
						page.getData(page.current);
					}
					utilObj.hideLoading();
				}
			});
    	},
    	follow:function(data,txt){
    		utilObj.showLoading();
    		utilObj.ajax({
				url: "cms/appoint/saveFollow",
				data:{
					userId:utilObj.getUser().userId,
					appoinId:data.id,
					followMemo:txt
				},
				success: function(data){
					if(data){
						page.getData(page.current);
					}
					utilObj.hideLoading();
				}
			});
    	},
    	exportData:function(data){
    		console.log(data);
    		var d={};
    		data.search_LIKE_phone!="" && (d.phone=data.search_LIKE_phone);
    		data.search_LIKE_name!="" && (d.name=data.search_LIKE_name);
    		data.search_EQ_store__country__id!="" && (d.countryId=data.search_EQ_store__country__id);
    		data.search_EQ_store__city__id!="" && (d.cityId=data.search_EQ_store__city__id)
    		data.search_EQ_store__id!="" && (d.storeId=data.search_EQ_store__id);
    		data.search_EQ_status!="" && (d.status=data.search_EQ_status);
    		
    		var createDate=data.createDate;
			if(createDate && createDate!=""){
				var t= createDate.split(' - ');
				d.startTime=t[0];
				d.endTime=t[1];
			}
    		data.search_EQ_store__id!="" && (d.storeId=data.search_EQ_store__id);
    		data.search_EQ_status!="" && (d.status=data.search_EQ_status);
    		
    		try{ 
	            var elemIF = document.createElement("iframe");   
	            elemIF.src = utilObj.ajaxURL+'cms/appoint/exportAppoint?'+setUrlK(d);   
	            elemIF.style.display = "none";   
	            document.body.appendChild(elemIF);   
	        }catch(e){ 
	 			
	        } 
	        function setUrlK(ojson) {
			    var s='',name, key;
			    for(var p in ojson) {
			        if(!ojson[p]) {return null;}
			        if(ojson.hasOwnProperty(p)) { name = p };
			        key = ojson[p];
			        s += "&" + name + "=" + encodeURIComponent(key);
			    };
			    return s.substring(1,s.length);
			};
    		
    	},
    	init:function(){
    		//时间控件
    		laydate.render({
			    elem: '#createDate',range: true
			});
			laydate.render({
			    elem: '#arriveDate',range: true
			});
			
			//三联动
			//获取省市区信息
		    if(!layer.cityList){
			    layui.utilObj.ajax({
					url: "cms/appoint/getCityList",
					success: function(data){
						if(data){
							layer.cityList2=data;
							var cityList={};
							layui.each(data,function(i,p){
								cityList[p.id]={name:p.country};
								layui.each(p.cityList,function(i,c){
									cityList[p.id][c.id]={name:c.cityName};
								});
							});
							layer.cityList=cityList;
							liandong();
						}
					}
				});
		    }
		    function liandong(){
				for(var obj of layer.cityList2){
					$("[name='search_EQ_store__country__id']").append(`<option value="${obj.id}">${obj.country}</option>`);
				}
				form.render('select',"country");
				
				form.on('select(select-country)', function(data){
					page.currentCountry=data.value;
					$("[name='search_EQ_store__city__id']").html(`<option value="">请选择城市</option>`);
					for(var obj in layer.cityList[data.value]){
						if(layer.cityList[data.value][obj].name) $("[name='search_EQ_store__city__id']").append(`<option value="${obj}">${layer.cityList[data.value][obj].name}</option>`);
					}
					form.render('select',"city");
				});
				form.on('select(select-city)', function(data){
					utilObj.ajax({
						url: "cms/appoint/getStoreList",
						data:{
							countryId:page.currentCountry,
							cityId:data.value
						},
						success: function(data){
							$("[name='search_EQ_store__id']").html(`<option value="">请选择店铺</option>`);
							if(data && data instanceof Array){
								for(var obj of data){
									if(obj.name)  $("[name='search_EQ_store__id']").append(`<option value="${obj.id}">${obj.name}</option>`);
								}
							}
							form.render('select',"store");
						}
					});
				}); 
		    }
			
//			page.getStore();
			page.getData(1);
			
    		//搜索
    		form.on('submit(submit)', function(data){
    			page.searchData=data.field;
				page.getData(1);
			    return false;
		    });
		    $(".btn_refresh").on("click",function(){
		    	page.getData(page.current);
		    });
		    //显示图片
		    $(document).on("dblclick",".table-cell-image",function(){
		    	var imgs=[];
		    	$(this).parent().children().each(function(){
		    		var t={
				      "alt": "",
				      "pid": new Date().valueOf(), //图片id
				      "src": $(this).attr("img"), 
				      "thumb": "" //缩略图地址
				    };
				    imgs.push(t);
		    	});
		    	layer.photos({
				    photos: {
					  "title": "",
					  "id": 1, 
					  "start": 0, 
					  "data": imgs
					},
					tab: function(pic, layero){
					}
				});
		    });
		    //导出
		    form.on('submit(submit2)', function(data){console.log(data);
		    	if(data.field.createDate.trim()==""){
		    		layer.open({
				        type: 1
				        ,title:"提示"
				        ,offset: 'auto' 
				        ,content: '<div style="padding: 20px 20px;">如不填写创建时间，默认导出三个月内数据。</div>'
				        ,btn: '导出'
				        ,btnAlign: 'c' //按钮居中
				        ,shade: 0 //不显示遮罩
				        ,yes: function(){
				        	page.exportData(data.field);
				            layer.closeAll();
				        }
				    });
		    	}else{
		    		page.exportData(data.field);
		    	}
			    return false;
		    });
    	},
    };
    page.init();
    
	//列表操作
    table.on('tool(list)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
		
		//暂时不做整合
        if(layEvent === 'process'){ //我来处理
            page.process(data);
        }
        else if(layEvent === 'accept'){//接受预约
        	page.accept(data);
        }
        else if(layEvent === 'cancel'){//取消预约
        	layer.open({
        		type:0,
        		area: ['450px', '250px'],
        		title:"取消预约",
        		content:`
        			<form class="layui-form layui-row" lay-filter="formCancel">
						<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
							<div class="layui-form-item">
								<label class="layui-form-label">取消原因</label>
								<div class="layui-input-block">
									<textarea name="cancelRemark" placeholder="请输入内容" class="layui-textarea"></textarea>
								</div>
							</div>
						</div>
					</form>
					<script>layui.form.render(null,"formCancel");</script>
        		`,
        		btn: ['确定', '取消'],
				yes: function(index, layero){
				    var remark = layero.find("[name='cancelRemark']").val();
				    page.cancel(data,remark);
				    layer.close(index);
				},
        	});
        }
        else if(layEvent === 'isArrive'){//是否到店
        	layer.open({
        		type:0,
        		area: ['400px', '300px'],
        		title:"是否到店",
        		content:`
        			<form class="layui-form layui-row" lay-filter="formIsArrive">
						<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
							<div class="layui-form-item">
								<label class="layui-form-label">是否到店</label>
								<div class="layui-input-block">
									<select name="sel-isArrive" lay-filter="select-isArrive">
										<option value="0">未到店</option>
										<option value="2">已到店未购买</option>
										<option value="1">已到店并购买</option>
									</select>
								</div>
							</div>
							<div class="layui-form-item div-isArriveReason">
								<label class="layui-form-label">未到店原因</label>
								<div class="layui-input-block">
									<textarea name="arriveRemark" placeholder="请输入内容" class="layui-textarea"></textarea>
								</div>
							</div>
						</div>
					</form>
					<script>
						layui.form.render(null,"formIsArrive");
						layui.form.on('select(select-isArrive)', function(data){
							if(data.value==0){
								$(".div-isArriveReason").show();
							}else{
								$(".div-isArriveReason").hide();
							}
						});      
					</script>
        		`,
        		btn: ['确定', '取消'],
				yes: function(index, layero){
				    var statusid = layero.find("[name='sel-isArrive']").val();
				    var remark = layero.find("[name='arriveRemark']").val();
				    var appointmentId=data.id;
				    page.arrive(appointmentId,statusid,remark);
				    layer.close(index);
				},
        	});
        }
        else if(layEvent === 'evaluate'){//评价
        	layer.open({
        		type:0,
        		area: ['450px', '350px'],
        		title:"评价",
        		content:`
        			<form class="layui-form layui-row" lay-filter="formEvaluate">
						<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
							<div class="layui-form-item">
								<label class="layui-form-label">满意度</label>
								<div class="layui-input-block">
									<div id="evaluateValue"></div>
								</div>
							</div>
							<div class="layui-form-item">
								<label class="layui-form-label">备注</label>
								<div class="layui-input-block">
									<textarea name="evaluateRemark" placeholder="请输入内容" class="layui-textarea"></textarea>
								</div>
							</div>
						</div>
					</form>
					<script>
						layui.config({
							base : "js/"
						}).extend({
						})
						layui.use(['rate'],function(){
							layui.rate.render({
							    elem: '#evaluateValue'
							});
						});
					</script>
        		`,
        		btn: ['确定', '取消'],
				yes: function(index, layero){
				    var star = layero.find(".layui-icon-rate-solid").length;
				    var remark = layero.find("textarea").val();
				    var appointmentId=data.id;
				    page.evaluate(appointmentId,star,remark);
				    layer.close(index);
				},
        	});
        }
        else if(layEvent === 'evaluateView'){//查看评价
        	layer.open({
        		type:0,
        		area: ['450px', '350px'],
        		title:"评价",
        		content:`
        			<form class="layui-form layui-row" lay-filter="formEvaluate">
						<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
							<div class="layui-form-item">
								<label class="layui-form-label">满意度</label>
								<div class="layui-input-block">
									<div id="evaluateValue"></div>
								</div>
							</div>
							<div class="layui-form-item">
								<label class="layui-form-label">备注</label>
								<div class="layui-input-block">
									<textarea readonly="readonly" name="evaluateRemark" placeholder="请输入内容" class="layui-textarea">${data.scoreMemo || ""}</textarea>
								</div>
							</div>
						</div>
					</form>
					<script>
						layui.use(['rate'],function(){
							layui.rate.render({
							    elem: '#evaluateValue'
							});
							var $ = layui.jquery;
							$(".layui-rate .layui-icon-rate").each(function(i){
								if(i<${data.score}){
									$(this).removeClass("layui-icon-rate");
									$(this).addClass("layui-icon-rate-solid");
								}
							});
							$(".layui-rate li").off("click");$(".layui-rate li").off("mousemove");$(".layui-rate li").off("mouseleave");
						});
					</script>
        		`,
        		btn: [],
        	});
        }
        else if(layEvent === 'reasonArrive'){//查看未到店原因
        	layer.open({
        		type:0,
        		area: ['450px', '250px'],
        		title:"未到店原因",
        		content:`
        			<form class="layui-form layui-row" lay-filter="formEvaluate">
						<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
							<div class="layui-form-item">
								<label class="layui-form-label">未到店原因</label>
								<div class="layui-input-block">
									<textarea readonly="readonly" class="layui-textarea">${data.noarriveReason || "" }</textarea>
								</div>
							</div>
						</div>
					</form>
        		`,
        		btn: [],
        	});
        }
        else if(layEvent === 'reasonCancel'){//查看取消原因
        	layer.open({
        		type:0,
        		area: ['450px', '250px'],
        		title:"取消原因",
        		content:`
        			<form class="layui-form layui-row" lay-filter="">
						<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
							<div class="layui-form-item">
								<label class="layui-form-label">取消原因</label>
								<div class="layui-input-block">
									<textarea readonly="readonly" class="layui-textarea">${data.rejectReason || "" }</textarea>
								</div>
							</div>
						</div>
					</form>
        		`,
        		btn: [],
        	});
        }
        else if(layEvent === 'append'){//跟进
        	layer.prompt({
			    formType: 2,
			    value: data.followMemo,
			    title: '跟进记录',
			    area: ['500px', '250px'] 
			}, function(value, index, elem){
				page.follow(data,value);
			    layer.close(index);
			});
        }
//      else if(layEvent === 'del'){ //删除
//          layer.confirm('确定删除此文章？',{icon:3, title:'提示信息'},function(index){
//              // $.get("删除文章接口",{
//              //     newsId : data.newsId  //将需要删除的newsId作为参数传入
//              // },function(data){
//                  tableIns.reload();
//                  layer.close(index);
//              // })
//          });
//      }
    });
	
	
})